package com.binarycube.webserver;



import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.ResourceHandler;

import com.binarycube.webserver.config.ConfigLoader;
import com.binarycube.webserver.config.DataManagerConfig;
import com.binarycube.webserver.config.ServerConfig;
import com.binarycube.webserver.datasource.DataManager;

public class WebServer {

	static Logger log = Logger.getLogger(WebServer.class.getName());
	ServerConfig config = null;
	DataManagerConfig dmc = null;
	Server server;
	
	
	
	public WebServer(){
		config = ConfigLoader.loadServerConfig();
		dmc = ConfigLoader.loadDataConfig();
		DataManager.init(dmc);
	}
	
	protected void reload(){
		config = ConfigLoader.loadServerConfig();
		dmc = ConfigLoader.loadDataConfig();
		DataManager dsm = DataManager.getInstance();
		dsm.clearCache();
		dsm.init(dmc);
		try {
			server.stop();
			server.start();
		} catch (Exception e) {
			log.error("Error restarting server.",e);
		}
		
	}
	
	public void start(){
		try {
			Server server = new Server();
	        ServerConnector connector = new ServerConnector(server);
	        connector.setPort(config.getPort());
	        server.addConnector(connector);
	 
	       
	        
	        ResourceHandler staticResourceHandler = new ResourceHandler();
	        staticResourceHandler.setDirectoriesListed(false);
	        staticResourceHandler.setResourceBase(config.getServerRoot());
	        
	      
	        
	        // Create context handler for static resource handler.
	        ContextHandler staticContextHandler = new ContextHandler();
	        staticContextHandler.setContextPath("/static");
	        staticContextHandler.setHandler(staticResourceHandler);
	   
	   	        
	        
	        ContextHandler pageContext = new ContextHandler();
	        pageContext.setContextPath("/");
	        pageContext.setHandler(new PageHandler(config));
	        
	        
	        ContextHandler scriptContext = new ContextHandler();
	        scriptContext.setContextPath("/script");
	        scriptContext.setHandler(new ScriptHandler(config));
	     
	        
	        
	        ContextHandler loginContext = new ContextHandler();
	        loginContext.setContextPath("/doLogin");
	        loginContext.setHandler(new LoginHandler(config));
	        
	        ContextHandler logoutContext = new ContextHandler();
	        logoutContext.setContextPath("/doLogout");
	        logoutContext.setHandler(new LogoutHandler(config));
	        
	        ContextHandler refreshContext = new ContextHandler();
	        refreshContext.setContextPath("/restart");
	        refreshContext.setHandler(new RefreshHandler(this));
	        
	        ContextHandlerCollection handlers = new ContextHandlerCollection();
	        handlers.setHandlers(new Handler[] { refreshContext, loginContext, logoutContext, pageContext,scriptContext, staticContextHandler});
	       
	        //Set the error handler for the server
	        server.addBean(new ServerErrorHandler());
	        server.setHandler(handlers);
	 
	      
	        
	        server.start();
	        server.join();
		} catch (Exception e) {
			log.error("Error starting " + config.getName(), e);
		}
        
	}
	
	public void stop(){
		new Thread()
		{
		   public void run() {
			   try {
					// server.setGracefulShutdown(100);
				     server.setStopAtShutdown(true);
			    	 log.info("Shutting down " + config.getName());
			    	 server.getServer().stop();
			        log.info(config.getName() + " has stopped.");
			     } catch (Exception ex) {
			    	 log.error("Error when stopping " + config.getName() +ex.getMessage(), ex);
			     }
		   }
		}.start();
	}

	public static void main(String[] args) {
		WebServer ws= new WebServer();
		ws.start();
	}
	
}
